package com.eportal.struts.action;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import mpi.client.data.OrderData;
import mpi.client.exception.PayException;
import mpi.client.trans.TopPayLink;
import mpi.client.tst.TstQueryTrans;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cfca.payment.api.system.PaymentEnvironment;
import cfca.util.Base64;

import com.eportal.ORM.CodeView;
import com.eportal.ORM.MpayAccount;
import com.eportal.ORM.MpayDkAccountInfo;
import com.eportal.ORM.MpayOrg;
import com.eportal.ORM.MpayPayinfo;
import com.eportal.ORM.MpayPosAllIn;
import com.eportal.ORM.MpayShop;
import com.eportal.ORM.MpayTradeFee;
import com.eportal.ORM.MpayUser;
import com.eportal.ORM.Mpayrespcode;
import com.eportal.ORM.NetPay;
import com.eportal.ORM.NetPayJnls;
import com.eportal.ORM.NetPayJnlsId;
import com.eportal.ORM.NetPayJnlsPl;
import com.eportal.ORM.UserView;
import com.eportal.ORM.WtPepJnls;
import com.eportal.ORM.WtPepJnlsBak;
import com.eportal.ORM.WtPepPayinfo;
import com.eportal.ORM.WtZfxtInfo;
import com.eportal.chinapay.SignData;
import com.eportal.core.BaseAction;
import com.eportal.core.Page;
import com.eportal.core.Payinfo;
import com.eportal.core.Trade;
import com.eportal.core.Util;
import com.eportal.gd.Conf;
import com.eportal.service.AdminService;
import com.eportal.thread.Dkpay;
import com.lowagie.tools.plugins.Txt2Pdf;

public class NetPayAction extends BaseAction {
	// static String shopno = "898440383981597";//安心
	public static String shopno = "898440383981524";// 华势

	AdminService service;
	AdminService serviceOracle;
	private Page page;
	private String start = "0";
	private String limit = "30";
	private boolean success;
	private String message;

	private String payRemark;
	private String payAmt;
	private String payInName;
	private String payInAccount;
	private String payInPhone;

	// 上传文件集合
	private List<File> file;
	// 上传文件名集合
	private List<String> fileFileName;
	// 上传文件内容类型集合
	private List<String> fileContentType;

	private String key;

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public List<File> getFile() {
		return file;
	}

	public void setFile(List<File> file) {
		this.file = file;
	}

	public List<String> getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}

	public List<String> getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getPayInPhone() {
		return payInPhone;
	}

	public void setPayInPhone(String payInPhone) {
		this.payInPhone = payInPhone;
	}

	private String payIdNo;

	public String getPayIdNo() {
		return payIdNo;
	}

	public void setPayIdNo(String payIdNo) {
		this.payIdNo = payIdNo;
	}

	private int id;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	private String flag;

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	String startDate = "";
	String endDate = "";

	public String getPayRemark() {
		return payRemark;
	}

	public void setPayRemark(String payRemark) {
		this.payRemark = payRemark;
	}

	public String getPayAmt() {
		return payAmt;
	}

	public void setPayAmt(String payAmt) {
		this.payAmt = payAmt;
	}

	public String getPayInName() {
		return payInName;
	}

	public void setPayInName(String payInName) {
		this.payInName = payInName;
	}

	public String getPayInAccount() {
		return payInAccount;
	}

	public void setPayInAccount(String payInAccount) {
		this.payInAccount = payInAccount;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public AdminService getService() {
		return service;
	}

	public void setService(AdminService service) {
		this.service = service;
	}

	public AdminService getServiceOracle() {
		return serviceOracle;
	}

	public void setServiceOracle(AdminService serviceOracle) {
		this.serviceOracle = serviceOracle;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public String getStart() {
		return start;
	}

	public void setStart(String start) {
		this.start = start;
	}

	public String getLimit() {
		return limit;
	}

	public void setLimit(String limit) {
		this.limit = limit;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String dkaccountinfo() {
		LOG.info("代扣导入商户信息...");
		UserView m = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		int s = Integer.valueOf(start);
		int l = Integer.valueOf(limit);
		String sql = "";
		sql += " where 1=1 ";
		if (m.getIsAll() != 1) {
			sql += " and orgcode = '" + m.getShopId() + "' ";
		}
		int start = 1;
		if (s != 0)
			start = s / 30 + 1;
		if (flag != null && !flag.equals("")) {
			sql += " and flag = 1 ";
		} else {
			sql += " and flag != 1 ";
		}
		if (payInAccount != null && !payInAccount.equals("")) {
			sql += " and concat(shop_code,bankAccount) like '%" + payInAccount
					+ "%' ";
		}
		sql += " order by flag ";
		System.out.println(sql);

		List userList = service
				.query("from MpayDkAccountInfo " + sql, start, l);
		page = new Page();
		page.setRoot(userList);
		page.setTotalProperty(service
				.countQuery("select count(*) from MpayDkAccountInfo" + sql));
		page.setStart(++s);
		page.setLimit(l = l == 0 ? 30 : l);
		return SUCCESS;
	}

	public String updateDk() {
		LOG.info("更新代扣账户表状态");
		if (flag == null || flag.equals("")) {
			message = "读取参数有误！";
			success = false;
		} else {
			try {
				if (flag.equals("1")) {
					this.getService().updateDkAccount(id);
				} else {
					MpayDkAccountInfo acc = (MpayDkAccountInfo) this.service
							.loadById(MpayDkAccountInfo.class, id);
					acc.setFlag(flag);
					this.service.saveOrUpdate(acc);
				}
				message = "已经更新";
				success = true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				message = "更新数据错误";
				success = false;
			}
		}
		return SUCCESS;
	}

	public String sendqklist() {
		String str[] = key.split(",");
		List<NetPayJnlsPl> tmp = new ArrayList<NetPayJnlsPl>();
		for (int i = 0; i < str.length; i++) {
			NetPayJnlsPl net = (NetPayJnlsPl) service.loadById(
					NetPayJnlsPl.class, Integer.valueOf(str[i]));
			net.setEntrycode("1");
			service.saveOrUpdate(net);
			tmp.add(net);
		}
		Dkpay dk = new Dkpay(tmp);
		dk.setService(service);
		dk.setServiceOracle(serviceOracle);
		dk.start();
		message = "已提交代扣，请等待片刻查询结果!";
		return SUCCESS;
	}

	public void uploadPl() {
		LOG.info("导入批量代扣文件");
		// System.out.println(file.size());
		// System.out.println(fileFileName.size());
		UserView m = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		int s = 0;
		int f = 0;
		File infile = file.get(0);
		String msg = "{success:true,message:'导入成功'}";
		try {
			String str = new String();
			POIFSFileSystem fs = new POIFSFileSystem(
					new FileInputStream(infile));
			HSSFWorkbook wb = new HSSFWorkbook(fs);
			HSSFSheet sheet = wb.getSheetAt(0);
			System.out.println("ROW:" + sheet.getLastRowNum());
			System.out.println("CELL:" + sheet.getRow(0).getLastCellNum());
			String value = "";

			for (short i = 1; i < sheet.getLastRowNum()+1; i++) {
				HSSFRow row = sheet.getRow(i);
				if (row == null)
					continue;
				for (short j = 0; j < row.getLastCellNum(); j++) {
					synchronized (this) {
						HSSFCell cell = row.getCell(j);
						if (cell == null)
							continue;
						switch (cell.getCellType()) {
						case HSSFCell.CELL_TYPE_NUMERIC:
							value = (int) cell.getNumericCellValue() + "";
							// getNumericCellValue()会回传double值，若不希望出现小数点，请自行转型为int
							break;
						case HSSFCell.CELL_TYPE_STRING:
							value = cell.getStringCellValue() + "";
							break;
						case HSSFCell.CELL_TYPE_FORMULA:
							value = cell.getNumericCellValue() + "";
							// 读出公式储存格计算後的值
							// 若要读出公式内容，可用cell.getCellFormula()
							break;
						default:
							// System.out.print( "不明的格式");
							break;
						}
						str += value + "|";
					}
				}
				str += "\r\n";
			}
			System.out.println(str);
			String[] sss = str.split("\r\n");
			for (int p = 0; p < sss.length; p++) {
				String ssss = sss[p];
				if (!ssss.equals("")) {
					String tmp[] = ssss.split("\\|");
					System.out.println("dfdf" + str);
					if (tmp.length == 4) {
						// System.out.println(str);

						List list = service
								.query(" from MpayAccount where rcv_cdno = '"
										+ tmp[1] + "' and rcv_term = '"
										+ m.getId() + "' ");
						if (list.size() == 1) {
							NetPayJnlsPl net = new NetPayJnlsPl();
							if (m.getShopName().indexOf("_") != -1) {
								net.setProdinfo(m.getShopName().substring(0,
										m.getShopName().indexOf("_"))
										.toUpperCase());
								net.setRemark(m.getShopName().substring(5)
										+ "[" + m.getMpayUserid() + "]");
							} else {
								net.setRemark(m.getShopName() + "["
										+ m.getMpayUserid() + "]");
							}
							net.setCustname(tmp[0]);
							net.setTrandatetime(new Date());
							net.setTranamt(Util.moveRightTwo(tmp[2]));
							net.setMsgext(tmp[3]);
							net.setPan(tmp[1].trim());
							net.setOrgcode(m.getId() + "");
							net.setPepdate(Util.getCurrentDate("yyyyMMdd"));
							if (Integer.valueOf(Util.moveRightTwo(tmp[2])) > 20000000
									|| Integer.valueOf(Util
											.moveRightTwo(tmp[2])) < 100) {
								f++;
							} else {
								service.save(net);
								s++;
							}
						} else {
							f++;
						}
					} else {
						f++;
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			msg = "{success:false,message:'导入失败请查看文件格式是否正确'}";
		}
		try {
			msg = "{success:true,message:'导入成功<br>成功:" + s + "失败:" + f + "'}";
			HttpServletResponse response = this.getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.getWriter().write(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String netpaypl() {
		LOG.info("批量代扣查询");
		UserView m = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		String sql = "";
		sql += " where ORGCODE = '" + m.getId() + "' and entrycode is null ";
		String sum = "";
		sum = service.sum("select sum(tranamt) from NetPayJnlsPl " + sql) + "";
		System.out.println(sum);
		// String sum =
		// service.countQuery("select sum(TRANAMT)/100 from NetPayJnlsPl" +
		// sql)+"";
		sql += " order by TRANDATETIME desc ";
		System.out.println(sql);
		List userList = service.query("from NetPayJnlsPl " + sql);
		List tmp = new ArrayList();
		for (int i = 0; i < userList.size(); i++) {
			NetPay net = new NetPay((NetPayJnlsPl) userList.get(i));
			net.setAllsum(Util.FormatSum(sum + ""));
			tmp.add(net);
		}
		page = new Page();
		page.setRoot(tmp);
		page.setTotalProperty(service
				.countQuery("select count(*) from NetPayJnlsPl" + sql));
		return SUCCESS;
	}

	public String deleteqldk() {
		LOG.info("删除批量代扣清单...");
		// System.out.println("[" + id + "]");
		String str[] = key.split(",");
		try {
			for (int i = 0; i < str.length; i++) {
				service.delById(NetPayJnlsPl.class, Integer.valueOf(str[i]));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			message = "删除代扣单错误！";
			success = false;
			return SUCCESS;
		}
		message = "删除代扣单成功！";
		success = true;
		return SUCCESS;
	}

	public String netpayinfo() {
		LOG.info("代扣明细查询...");
		UserView m = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		int s = Integer.valueOf(start);
		int l = Integer.valueOf(limit);
		String sql = "";
		if (m.getIsAll() == 1) {
			sql += " where (trancode = '1040' or trancode = '0003') ";
		} else if (m.getShopName().startsWith("tt")) {
			sql += " where (trancode = '1040' or trancode = '0003') and PRODINFO = '"
					+ m.getShopName()
							.substring(0, m.getShopName().indexOf("_"))
							.toUpperCase() + "' ";
		} else {
			sql += " where (trancode = '1040' or trancode = '0003') and orgcode = '"
					+ m.getId() + "' ";
		}
		startDate = startDate == null ? "" : startDate.trim();
		endDate = endDate == null ? "" : endDate.trim();
		if (!startDate.equals("") && !endDate.equals("")) {
			sql += " and (pepdate between '" + startDate + "' and '" + endDate
					+ "') ";
		}
		int start = 1;
		if (s != 0)
			start = s / 30 + 1;
		// System.out.println(sql);
		String sumsql = "select sum(tranamt)/100 from Net_Pay_Jnls " + sql
				+ " and (respcode = '000000' or respcode = '00') ";
		String sum = "0";
		Connection c = serviceOracle.getConnection();
		try {
			System.out.println(sumsql);
			PreparedStatement ps = c.prepareStatement(sumsql);
			ResultSet rs = ps.executeQuery();
			rs.next();
			sum = rs.getString(1);
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sql += " order by TRANDATETIME desc ";
		System.out.println(sql);
		List userList = serviceOracle.query("from NetPayJnls " + sql, start, l);
		List tmp = new ArrayList();
		for (int i = 0; i < userList.size(); i++) {
			NetPay net = new NetPay((NetPayJnls) userList.get(i));
			net.setAllsum(sum);
			tmp.add(net);
		}
		page = new Page();
		page.setRoot(tmp);
		page.setTotalProperty(serviceOracle
				.countQuery("select count(*) from NetPayJnls" + sql));
		page.setStart(++s);
		page.setLimit(l = l == 0 ? 30 : l);
		return SUCCESS;
	}

	public String checkId() {
		LOG.info("发送实名认证报文");
		UserView m = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		String MPIURL = Util.ROOTPATH + "/netPay/MPI.properties";
		System.out.println(MPIURL);
		try {
			System.setProperty("javax.net.ssl.trustStore", Util.ROOTPATH
					+ "/netPay/jssecacerts");
			TopPayLink.setMPIpropertiesFilePath(MPIURL);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Random random = new Random();
		int id = random.nextInt(99999999);
		OrderData tstOrderData = new OrderData();
		// 以下字段是无密实名认证交易必输字段
		// 无密实名认证交易码：4021
		tstOrderData.setTranCode("4021");
		// 商户ＩＤ（每个商户对应唯一的ID）
		tstOrderData.setMerchantID(shopno);
		// 交易时间(注意位数:14位，交易时间和系统当前时间相差不超过2个小时)：20101125112433
		tstOrderData.setTranDateTime(Util.getCurrentDate("yyyyMMddHHmmss"));
		// 订单号（生成规则：从商户ID第四位开始的四位[4401]+取商户ID倒数四位[0027]+8位随机序列号）
		tstOrderData.setMerOrderNum("4038" + "1597" + Util.addZero("" + id, 8));
		// 卡号
		tstOrderData.setPan(payInAccount.replace(" ", ""));
		// 持卡人信息(01(证件类别)+310123198808083821(证件编号)+zhangsan(姓名))
		tstOrderData.setChInfo("01" + payIdNo, payInName, "", "", "", "");
		// 以下字段是无密实名认证交易可输字段
		tstOrderData.setMsgExt("附加信息");
		NetPayJnls net = new NetPayJnls();
		net.setCustname(tstOrderData.getCustName());
		net.setTrancode("4021");
		net.setMerchantid(tstOrderData.getMerchantID());
		net.setMsgext(tstOrderData.getMsgExt());
		net.setOrgcode(m.getId() + "");
		net.setChinfo(tstOrderData.getChInfo());
		net.setPan(tstOrderData.getPan());
		net.setRespcode("SS");
		net.setRespdesc("发送超时");
		message = "发送超时";
		if (m.getShopName().indexOf("_") != -1) {
			net.setProdinfo(m.getShopName().substring(0,
					m.getShopName().indexOf("_")).toUpperCase());
			net.setRemark(m.getShopName().substring(5) + "["
					+ m.getMpayUserid() + "]");
		} else {
			net.setRemark(m.getShopName() + "[" + m.getMpayUserid() + "]");
		}
		net.setTranamt(tstOrderData.getTranAmt());
		net.setTrandatetime(new Timestamp(new Date().getTime()));

		NetPayJnlsId nid = new NetPayJnlsId();
		nid.setPepdate(tstOrderData.getTranDateTime().substring(0, 8));
		nid.setMerordernum(tstOrderData.getMerOrderNum());
		net.setId(nid);
		this.serviceOracle.save(net);
		try {
			// 调用交易接口发送到中国银联互联网收单服务平台并同步接收返回结果
			// 商户可根据返回结果进行相关后续处理
			tstOrderData = TopPayLink.RemitTrans(tstOrderData);
			if (tstOrderData == null) {
				System.out.println("TopPayLink.RemitTrans error");
			} else {
				// 打印返回交易结果码,返回6个0(000000)表示交易成功
				// 其他的交易码可参考MPI商户插件文档（附录一）.
				System.out.println("Txn RespCode is : "
						+ tstOrderData.getRespCode());
			}
		} catch (PayException ex) {
			System.out.println("TopPayLink.RemitTrans error: RespCode =["
					+ ex.getErrCd() + "]");
			tstOrderData.setRespCode(ex.getErrCd());
			ex.printStackTrace();
			message = "发送失败，请稍候在试！";
			success = false;
			return SUCCESS;
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("TopPayLink.CollPayTrans error 2");
			message = "发送失败，请稍候在试！";
			success = false;
			return SUCCESS;
		}
		Connection c = serviceOracle.getConnection();
		try {
			PreparedStatement ps = c
					.prepareStatement("update net_pay_jnls set RESPCODE = '"
							+ tstOrderData.getRespCode() + "',CUPSSYSTIME  = '"
							+ tstOrderData.getCupsSysTime()
							+ "',CUPSTRACENUM = '"
							+ tstOrderData.getCupsTraceNum()
							+ "',SETTLEDATE = '" + tstOrderData.getSettleDate()
							+ "',RESPDESC = '" + tstOrderData.getRespDesc()
							+ "' where MERORDERNUM = '"
							+ tstOrderData.getMerOrderNum()
							+ "' and PEPDATE = '"
							+ Util.getCurrentDate("yyyyMMdd") + "'");
			ps.executeUpdate();
			c.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (tstOrderData.getRespCode().equals("000000")) {
			message = "结果：认证成功！";
		} else {
			message = "结果：" + tstOrderData.getRespDesc();
		}
		success = true;
		return SUCCESS;
	}

	public String sendsmsdk() {
		LOG.info("发送SMS代扣");
		try {
			new Conf(Util.ROOTPATH + "/webPay/");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			message = "登录超时，请重新登录！";
			success = false;
			return SUCCESS;
		}
		UserView m = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		Random random = new Random();
		int id = random.nextInt(99999999);
		String sms = Conf.SMS_DK;
		String mobile = payInPhone;
		System.out.println(payInAccount + " " + sms);
		String str = checkBin(payInAccount, "1");
		if (str.equals("")) {
			message = "该卡不支持该交易";
			success = false;
			return SUCCESS;
		}
		System.out.println("check" + str);
		char isDk = str.charAt(0);
		char qdao = str.charAt(1);
		String bank = str.substring(2);
		sms = sms.replace("#A", bank
				+ payInAccount.substring(payInAccount.length() - 4));
		sms = sms.replace("#B", payAmt);
		sms = sms.replace("#C", payRemark);
		if (isDk == '1') {// 支持代扣
			if (qdao == '0') {// 互联网渠
				OrderData tstOrderData = new OrderData();
				// 以下字段是无密代扣交易必输字段
				tstOrderData.setTranCode("1040");
				// 商户ＩＤ（每个商户对应唯一的ID）
				tstOrderData.setMerchantID(shopno);
				// 订单号（生成规则：从商户ID第四位开始的四位[4401]+取商户ID倒数四位[0027]+8位随机序列号）
				tstOrderData.setMerOrderNum("4038" + "1597"
						+ Util.addZero("" + id, 8));
				// 交易时间(注意位数:14位，交易时间和系统当前时间相差不超过2个小时)：20101125112433
				tstOrderData.setTranDateTime(Util
						.getCurrentDate("yyyyMMddHHmmss"));
				tstOrderData.setPan(payInAccount);
				// 币种（人民币：156）
				tstOrderData.setCurType("156");
				// 交易金额(单位：分)
				tstOrderData.setTranAmt(Util.moveRightTwo(payAmt));
				tstOrderData.setChInfo("", "", "", "", "", "");
				// 以下字段是无密代扣交易可输字段
				tstOrderData.setCustName(payInName);
				// tstOrderData.setMsgExt(payRemark);
				NetPayJnls net = new NetPayJnls();
				net.setCustname(tstOrderData.getCustName());
				net.setTrancode("1040");
				net.setMerchantid(tstOrderData.getMerchantID());
				net.setMsgext(payRemark);
				net.setOrgcode(m.getId() + "");
				net.setPan(tstOrderData.getPan());
				net.setRespcode("FF");
				net.setRespdesc("待短信确认");
				net.setCustemail(sms);

				net.setIssbin(mobile);
				if (m.getShopName().indexOf("_") != -1) {
					net.setProdinfo(m.getShopName().substring(0,
							m.getShopName().indexOf("_")).toUpperCase());
					net.setRemark(m.getShopName().substring(5) + "["
							+ m.getMpayUserid() + "]");
				} else {
					net.setRemark(m.getShopName() + "[" + m.getMpayUserid()
							+ "]");
				}
				net.setTranamt(tstOrderData.getTranAmt());
				net.setTrandatetime(new Timestamp(new Date().getTime()));
				NetPayJnlsId nid = new NetPayJnlsId();
				nid.setPepdate(tstOrderData.getTranDateTime().substring(0, 8));
				nid.setMerordernum(tstOrderData.getMerOrderNum());
				net.setId(nid);
				try {
					this.serviceOracle.save(net);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					message = "生成订单失败！";
					success = false;
					return SUCCESS;
				}
			} else {// chinapay渠道
				String merId = "808080450004842";
				String transDate = Util.getCurrentDate("yyyyMMdd");
				String orderNo = "50004842" + Util.addZero("" + id, 8);
				String transType = "0003";
				String openBankId = Util.checkBank(bank.trim());
				String cardType = "0";
				String cardNo = payInAccount;
				String usrName1 = payInName;
				String tianUn = toUnicode(usrName1);
				String tmpUsrName = tianUn;
				String certType = "01";
				String certId = "310000000000000000";
				String curyId = "156";
				String transAmt = Util
						.left_(Util.moveRightTwo(payAmt), "0", 12);
				String purpose = "";
				String priv1 = "00";
				String tmpPriv1 = toUnicode(priv1);
				String version = "20100831";
				String gateId = "7008";
				NetPayJnls net = new NetPayJnls();
				net.setCustname(payInName);
				net.setTrancode("0003");
				net.setMerchantid(merId);
				net.setMsgext(payRemark);
				net.setOrgcode(m.getId() + "");
				net.setPan(payInAccount);
				net.setCustemail(sms);

				net.setIssbin(mobile);
				net.setRespcode("FF");
				net.setRespdesc("待短信确认");
				if (m.getShopName().indexOf("_") != -1) {
					net.setProdinfo(m.getShopName().substring(0,
							m.getShopName().indexOf("_")).toUpperCase());
					net.setRemark(m.getShopName().substring(5) + "["
							+ m.getMpayUserid() + "]");
				} else {
					net.setRemark(m.getShopName() + "[" + m.getMpayUserid()
							+ "]");
				}
				net.setTranamt(Util.left_(Util.moveRightTwo(payAmt), "0", 12));
				net.setTrandatetime(new Timestamp(new Date().getTime()));
				NetPayJnlsId nid = new NetPayJnlsId();
				nid.setPepdate(transDate);
				nid.setMerordernum(orderNo);
				net.setId(nid);
				try {
					this.serviceOracle.save(net);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					message = "生成订单失败！";
					success = false;
					return SUCCESS;
				}
			}

			try {
				Util.sendSMSToServer(mobile, sms, "9");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			message = "生成订单成功！";
			success = true;
			return SUCCESS;
		} else {
			message = "不支持代扣！";
			success = false;
			return SUCCESS;
		}
	}

	public String senddk() {
		LOG.info("发送代扣报文");
		UserView m = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");

		Random random = new Random();
		int id = random.nextInt(99999999);
		// 判定代扣渠道
		String str = checkBin(payInAccount, "1");
		char isDk = '0';
		char qdao = '0';
		String bank = "";
		try {
			isDk = str.charAt(0);
			qdao = str.charAt(1);
			bank = str.substring(2);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			message = "不支持该银行卡，如有疑问，联系客服。";
			success = false;
			return SUCCESS;
		}
		if (isDk == '1') {// 支持代扣
			if (qdao == '0') {// 互联网渠道
				String MPIURL = Util.ROOTPATH + "/netPay/MPI.properties";
				System.out.println(MPIURL);
				try {
					System.setProperty("javax.net.ssl.trustStore",
							Util.ROOTPATH + "/netPay/jssecacerts");
					TopPayLink.setMPIpropertiesFilePath(MPIURL);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				OrderData tstOrderData = new OrderData();
				// 以下字段是无密代扣交易必输字段
				tstOrderData.setTranCode("1040");
				// 商户ＩＤ（每个商户对应唯一的ID）
				tstOrderData.setMerchantID(shopno);
				// 订单号（生成规则：从商户ID第四位开始的四位[4401]+取商户ID倒数四位[0027]+8位随机序列号）
				tstOrderData.setMerOrderNum("4038" + "1597"
						+ Util.addZero("" + id, 8));
				// 交易时间(注意位数:14位，交易时间和系统当前时间相差不超过2个小时)：20101125112433
				tstOrderData.setTranDateTime(Util
						.getCurrentDate("yyyyMMddHHmmss"));
				tstOrderData.setPan(payInAccount);
				// 币种（人民币：156）
				tstOrderData.setCurType("156");
				// 交易金额(单位：分)
				tstOrderData.setTranAmt(Util.moveRightTwo(payAmt));
				tstOrderData.setChInfo("", "", "", "", "", "");
				// 以下字段是无密代扣交易可输字段
				tstOrderData.setCustName(payInName);
				// tstOrderData.setMsgExt(payRemark);
				NetPayJnls net = new NetPayJnls();
				net.setCustname(tstOrderData.getCustName());
				net.setTrancode("1040");
				net.setMerchantid(tstOrderData.getMerchantID());
				net.setMsgext(payRemark);
				net.setOrgcode(m.getId() + "");
				net.setPan(tstOrderData.getPan());
				net.setRespcode("SS");

				net.setRespdesc("发送超时");
				if (m.getShopName().indexOf("_") != -1) {
					net.setProdinfo(m.getShopName().substring(0,
							m.getShopName().indexOf("_")).toUpperCase());
					net.setRemark(m.getShopName().substring(5) + "["
							+ m.getMpayUserid() + "]");
				} else {
					net.setRemark(m.getShopName() + "[" + m.getMpayUserid()
							+ "]");
				}
				net.setTranamt(tstOrderData.getTranAmt());
				net.setTrandatetime(new Timestamp(new Date().getTime()));

				NetPayJnlsId nid = new NetPayJnlsId();
				nid.setPepdate(tstOrderData.getTranDateTime().substring(0, 8));
				nid.setMerordernum(tstOrderData.getMerOrderNum());
				net.setId(nid);
				this.serviceOracle.save(net);
				try {
					// 调用交易接口发送到中国银联互联网收单服务平台并同步接收返回结果
					// 商户可根据返回结果进行相关后续处理
					tstOrderData = TopPayLink.CollPayTrans(tstOrderData);

					if (tstOrderData == null) {
						System.out.println("TopPayLink.CollPayTrans error");
					} else {
						// 打印返回交易结果码,返回6个0(000000)表示交易成功
						// 其他的交易码可参考MPI商户插件文档（附录一）.
						System.out.println("Txn RespCode is : "
								+ tstOrderData.getRespCode());
					}
				} catch (PayException ex) {
					System.out
							.println("TopPayLink.CollPayTrans error: RespCode =["
									+ ex.getErrCd() + "]");
					tstOrderData.setRespCode(ex.getErrCd());
					ex.printStackTrace();
					message = "发送失败，请稍候在试！";
					success = false;
					return SUCCESS;
				} catch (Exception ex) {
					ex.printStackTrace();
					System.out.println("TopPayLink.CollPayTrans error 2");
					message = "发送失败，请稍候在试！";
					success = false;
					return SUCCESS;
				}
				Connection c = serviceOracle.getConnection();
				try {
					PreparedStatement ps = c
							.prepareStatement("update net_pay_jnls set RESPCODE = '"
									+ tstOrderData.getRespCode()
									+ "',CUPSSYSTIME  = '"
									+ tstOrderData.getCupsSysTime()
									+ "',CUPSTRACENUM = '"
									+ tstOrderData.getCupsTraceNum()
									+ "',SETTLEDATE = '"
									+ tstOrderData.getSettleDate()
									+ "',RESPDESC = '"
									+ tstOrderData.getRespDesc()
									+ "' where MERORDERNUM = '"
									+ tstOrderData.getMerOrderNum()
									+ "' and PEPDATE = '"
									+ Util.getCurrentDate("yyyyMMdd") + "'");
					ps.executeUpdate();
					c.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {// chinapay渠道
				HttpClient httpClient = new HttpClient();
				httpClient.getParams().setParameter(
						HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
				String url = "http://apps.chinapay.com/witsingletran/WitSinTranServlet";
				PostMethod postMethod = new PostMethod(url);
				String merId = "808080450004842";
				String transDate = Util.getCurrentDate("yyyyMMdd");
				String orderNo = "50004842" + Util.addZero("" + id, 8);
				String transType = "0003";
				String openBankId = Util.checkBank(bank.trim());
				String cardType = "0";
				String cardNo = payInAccount;
				String usrName1 = payInName;
				String tianUn = toUnicode(usrName1);
				String tmpUsrName = tianUn;
				String certType = "01";
				String certId = "310000000000000000";
				String curyId = "156";
				String transAmt = Util
						.left_(Util.moveRightTwo(payAmt), "0", 12);
				String purpose = "";
				String priv1 = "00";
				String tmpPriv1 = toUnicode(priv1);
				String version = "20100831";
				String gateId = "7008";

				StringBuffer retStr = new StringBuffer();
				retStr.append(merId).append(transDate).append(orderNo).append(
						transType).append(openBankId).append(cardType).append(
						cardNo).append(tmpUsrName).append(certType).append(
						certId).append(curyId).append(transAmt)
						.append(tmpPriv1).append(version).append(gateId);

				SignData signData = new SignData();
				if (Util.ROOTPATH.equals("")) {
					message = "登录超时，请重新登录！";
					success = false;
					return SUCCESS;
				}
				signData.setPath(Util.ROOTPATH + "/chinapay/");
				String data0 = new String(Base64.encode(retStr.toString()
						.getBytes()));
				String chkValue = signData.signForCP(merId, data0);
				NameValuePair[] data = { new NameValuePair("merId", merId),
						new NameValuePair("transDate", transDate),
						new NameValuePair("orderNo", orderNo),
						new NameValuePair("transType", transType),
						new NameValuePair("openBankId", openBankId),
						new NameValuePair("cardType", cardType),
						new NameValuePair("cardNo", cardNo),
						new NameValuePair("usrName", tmpUsrName),
						new NameValuePair("certType", certType),
						new NameValuePair("certId", certId),
						new NameValuePair("curyId", curyId),
						new NameValuePair("transAmt", transAmt),
						new NameValuePair("purpose", purpose),
						new NameValuePair("priv1", tmpPriv1),
						new NameValuePair("version", version),
						new NameValuePair("gateId", gateId),
						new NameValuePair("chkValue", chkValue) };

				postMethod.setRequestBody(data);
				NetPayJnls net = new NetPayJnls();
				net.setCustname(payInName);
				net.setTrancode("0003");
				net.setMerchantid(merId);
				net.setMsgext(payRemark);
				net.setOrgcode(m.getId() + "");
				net.setPan(payInAccount);
				net.setRespcode("SS");

				net.setRespdesc("发送超时");
				if (m.getShopName().indexOf("_") != -1) {
					net.setProdinfo(m.getShopName().substring(0,
							m.getShopName().indexOf("_")).toUpperCase());
					net.setRemark(m.getShopName().substring(5) + "["
							+ m.getMpayUserid() + "]");
				} else {
					net.setRemark(m.getShopName() + "[" + m.getMpayUserid()
							+ "]");
				}
				net.setTranamt(Util.left_(Util.moveRightTwo(payAmt), "0", 12));
				net.setTrandatetime(new Timestamp(new Date().getTime()));

				NetPayJnlsId nid = new NetPayJnlsId();
				nid.setPepdate(transDate);
				nid.setMerordernum(orderNo);
				net.setId(nid);
				this.serviceOracle.save(net);
				int statusCode = 0;
				try {
					statusCode = httpClient.executeMethod(postMethod);
				} catch (HttpException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (statusCode != HttpStatus.SC_OK) {
					System.out.println("Method failed:"
							+ postMethod.getStatusLine());
				}
				String tian = "";
				String responseCode = "";
				try {
					tian = postMethod.getResponseBodyAsString();
					System.out.println("html:" + tian);
					responseCode = tian.substring(13, 15);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String msg = "";

				if (!responseCode.equals("")) {
					if (!responseCode.equals("45")) {
						msg = (String) Util.CHINALIST.get(responseCode);
					} else {
						String tiakong = tian;
						int dex = tian.lastIndexOf("=");

						String tmp = "";
						String tmp2 = "";
						if (tiakong.indexOf("message") != -1) {
							msg = tiakong
									.substring(tiakong.indexOf("message") + 8);
							tmp = tiakong.substring(0, tiakong
									.indexOf("message") + 8);
							tmp2 = msg.substring(msg.indexOf("&", 1));
							msg = msg.substring(0, msg.indexOf("&", 1));
						}
						msg = tozhCN(msg);
					}
					if (msg == null || msg.equals(""))
						msg = "交易失败";
					Connection c = serviceOracle.getConnection();
					try {
						PreparedStatement ps = c
								.prepareStatement("update net_pay_jnls set RESPCODE = '"
										+ responseCode
										+ "',RESPDESC = '"
										+ msg
										+ "' where MERORDERNUM = '"
										+ orderNo
										+ "' and PEPDATE = '"
										+ Util.getCurrentDate("yyyyMMdd") + "'");
						ps.executeUpdate();
						c.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			message = "付款成功！";
			success = true;
			return SUCCESS;
		} else {
			message = "不支持代扣！";
			success = false;
			return SUCCESS;
		}
	}

	public InputStream excelToDk() {
		LOG.info("下载代扣明细数据...");
		UserView m = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		String sql = "";
		if (m.getIsAll() == 1) {
			sql += " where (trancode = '1040' or trancode = '0003')";
		} else if (m.getShopName().startsWith("tt")) {
			sql += " where (trancode = '1040' or trancode = '0003') and PRODINFO = '"
					+ m.getShopName()
							.substring(0, m.getShopName().indexOf("_"))
							.toUpperCase() + "' ";
		} else {
			sql += " where (trancode = '1040' or trancode = '0003') and orgcode = '"
					+ m.getId() + "' ";
		}
		startDate = startDate == null ? "" : startDate.trim();
		endDate = endDate == null ? "" : endDate.trim();
		if (!startDate.equals("") && !endDate.equals("")) {
			sql += " and (pepdate between '" + startDate + "' and '" + endDate
					+ "') ";
		}
		// System.out.println(sql);
		sql += " order by TRANDATETIME desc";
		System.out.println(sql);
		List userList = serviceOracle.query("from NetPayJnls" + sql);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("new sheet");
		HSSFRow row = sheet.createRow((short) 0);
		HSSFCell cell = row.createCell((short) 0);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("付款时间");
		cell = row.createCell((short) 1);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("付款账号");
		cell = row.createCell((short) 2);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("付款人");
		cell = row.createCell((short) 3);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("金额");
		cell = row.createCell((short) 4);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("应答码");
		cell = row.createCell((short) 5);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("应答解释");
		cell = row.createCell((short) 6);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("备注");
		cell = row.createCell((short) 7);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("流水号");
		cell = row.createCell((short) 8);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("清算日期");
		cell = row.createCell((short) 9);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("订单号");
		cell = row.createCell((short) 10);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue("网点名称");
		Iterator itr = userList.iterator();
		short rowNum = 1;
		NetPayJnls w;
		while (itr.hasNext()) {
			row = sheet.createRow(rowNum);
			w = (NetPayJnls) itr.next();
			cell = row.createCell((short) 0);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(sf.format(w.getTrandatetime()));
			cell = row.createCell((short) 1);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(Util.toInCard(w.getPan()));
			cell = row.createCell((short) 2);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(w.getCustname());
			cell = row.createCell((short) 3);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(Util.FormatSum(w.getTranamt()));
			cell = row.createCell((short) 4);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(w.getRespcode());
			cell = row.createCell((short) 5);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(w.getRespdesc());
			cell = row.createCell((short) 6);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(w.getMsgext());
			cell = row.createCell((short) 7);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(w.getCupstracenum());
			cell = row.createCell((short) 8);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(w.getSettledate());
			cell = row.createCell((short) 9);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(w.getId().getMerordernum());
			cell = row.createCell((short) 10);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(w.getRemark());
			rowNum++;
		}
		try {
			OutputStream out = this.getResponse().getOutputStream();
			this.getResponse().setHeader("Content-disposition",
					"attachment; filename=data.xls");
			this.getResponse().setContentType(
					"application/msexcel;charset=UTF-8");
			wb.write(out);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public void payrec() {
		LOG.info("接收CFCA应答");
		String TxCode = "";
		String PaymentNo = "";
		String SuccessTime = "";
		String Status = "";
		try {
			InputStream is = this.getRequest().getInputStream();
			byte tmp[] = new byte[200];
			is.read(tmp);
			System.out.println(new String(tmp));
			String path = this.getServletContext().getRealPath("/");
			if (path != null)
				path = path.replaceAll("\\\\", "/");
			else
				path = "/";
			if (!path.endsWith("/"))
				path = path + "/";
			Util.ROOTPATH = path;
			PaymentEnvironment.initialize(Util.ROOTPATH + "/webPay/");
			String msg = this.getRequest().getParameter("message");
			String sign = this.getRequest().getParameter("signature");
			String txt = new String(Base64.decode(msg), "UTF-8");
			System.out.println("CFCA:" + txt);
			SAXReader reader = new SAXReader();
			Document doc = null;
			try {
				doc = reader.read(new ByteArrayInputStream(txt.getBytes()));
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Element root = doc.getRootElement();
			Element foo;
			for (Iterator i = root.elementIterator(); i.hasNext();) {
				Element harder = (Element) i.next();
				if (harder.elementText("TxCode") != null)
					TxCode = harder.elementText("TxCode");
				if (harder.elementText("PaymentNo") != null)
					PaymentNo = harder.elementText("PaymentNo");
				if (harder.elementText("SuccessTime") != null)
					SuccessTime = harder.elementText("SuccessTime");
				if (harder.elementText("Status") != null)
					Status = harder.elementText("Status");
			}
			if (TxCode.equals("1318")) {
				Connection c = serviceOracle.getConnection();
				PreparedStatement ps = c
						.prepareStatement("update net_pay_jnls set RESPCODE = '"
								+ Status
								+ "',CUPSSYSTIME  = '"
								+ SuccessTime
								+ "' where CUPSTRACENUM = '" + PaymentNo + "'");
				ps.executeUpdate();

				c.close();
			}
			// if(txt!=null&&!txt.equals("")){
			// OutputStream os = this.getResponse().getOutputStream();
			// String yd =
			// "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response version=\"2.0\"><Head><Code>2000</Code><Message>成功受理了请求。</Message></Head></Response>";
			// String requestMessage = new
			// String(Base64.encode(yd.getBytes("UTF-8")));
			// Tx134xResponse
			// String requestSignature = "";
			// try {
			// requestSignature =
			// SignatureFactory.getSigner().sign(requestMessage);
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// String out =
			// "message="+URLEncoder.encode(requestMessage)+"&signature="+URLEncoder.encode(requestSignature);
			// os.write(out.getBytes());
			// os.close();
			// }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 校验卡BIN
	public String checkBin(String card, String flag) {
		String sql = "select t.net_iss_flag,t.net_iss_card,p.lc_card,NET_ISS_RZ,NET_ISS_DK,NET_ISS_NAME from net_pay_iss t, pep_card_limit p where t.net_iss_id = trim(p.lc_iss_id) and length(trim('"
				+ card
				+ "')) = p.lc_cdnopos and substr(trim('"
				+ card
				+ "'),0,length(trim(p.lc_head)))= trim(p.lc_head)";
		Connection c = serviceOracle.getConnection();
		String tmp = "";
		try {
			PreparedStatement ps = c.prepareStatement(sql);
			ResultSet rset = ps.executeQuery();
			rset.next();
			String net_iss_flag = rset.getString(1);
			String net_iss_card = rset.getString(2);
			String lc_card = rset.getString(3);
			String net_rz = rset.getString(4);
			String net_dk = rset.getString(5);
			String net_name = rset.getString(6);
			if (flag.equals("0")) {// 消费
				if (net_iss_flag.equals("0") || net_iss_flag.equals("2")) {
					if (lc_card.equals("D")) {
						if (net_iss_card.equals("0")
								|| net_iss_card.equals("2")) {
							tmp = 1 + net_dk;
						}
					} else {
						if (net_iss_card.equals("1")
								|| net_iss_card.equals("2")) {
							tmp = 1 + net_dk;
						}
					}
				}
			} else if (flag.equals("1")) {// 代扣
				if (net_iss_flag.equals("1") || net_iss_flag.equals("2")) {
					if (lc_card.equals("D")) {
						if (net_iss_card.equals("0")
								|| net_iss_card.equals("2")) {
							tmp = 1 + net_dk + net_name;
						}
					} else {
						if (net_iss_card.equals("1")
								|| net_iss_card.equals("2")) {
							tmp = 1 + net_dk + net_name;
						}
					}
				}
			} else if (flag.equals("2")) {// 认证
				if (net_rz != null && net_rz.equals("1")) {
					tmp = 1 + net_dk;
				} else {
					tmp = 0 + net_dk;
				}
			}
			c.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tmp = "00";
		}

		return tmp;
	}

	public static String tozhCN(String unicode) {
		StringBuffer gbk = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
		for (int i = 1; i < hex.length; i++) {
			int data = Integer.parseInt(hex[i], 16);
			gbk.append((char) data);
		}
		return gbk.toString();
	}

	public static String toUnicode(String zhStr) {
		StringBuffer unicode = new StringBuffer();
		for (int i = 0; i < zhStr.length(); i++) {
			char c = zhStr.charAt(i);
			unicode.append("\\u" + Integer.toHexString(c));
		}
		System.out.println(unicode.toString());
		return unicode.toString();
	}

}
